import os
import re
import aiofiles
import logging
from typing import Optional
from pathlib import Path
CURRENT_DIR = Path(__file__).resolve()
PROJECT_TOP = CURRENT_DIR.parents[3]
LOG_DIR = PROJECT_TOP / "logs"
LOG_FILE = LOG_DIR / "station_service.log"
LOG_DIR.mkdir(exist_ok=True)
logging.basicConfig(
            level=logging.INFO,  # 设置日志级别为INFO，这样INFO及以上级别日志会显示
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            handlers=[
                logging.FileHandler(LOG_FILE, encoding='utf-8')
            ]
        )
JS_PATH = PROJECT_TOP / "mcpserver12306" / "src" / "resources" / "station_name.js"
class Station:
    def __init__(self, name, code, pinyin, py_short, num, city=None):
        self.name = name
        self.code = code
        self.pinyin = pinyin
        self.py_short = py_short
        self.num = num
        self.city = city  # 城市字段可选

    def __repr__(self):
        return f"Station(name={self.name}, code={self.code}, pinyin={self.pinyin}, city={self.city})"
    # 增加一个方法用于调试输出
    def to_dict(self):
        return {
            'name': self.name,
            'code': self.code,
            'pinyin': self.pinyin,
            'py_short': self.py_short,
            'num': self.num,
            'city': self.city
        }
class StationSearchResult:
    def __init__(self, stations):
        self.stations = stations

class StationService:
    def __init__(self):
        self.stations = []
        self.logger = logging.getLogger(__name__)

    async def load_stations(self, path=JS_PATH):
        """
        解析12306原始JS，提取站点及所属城市信息
        自动检测并修复字段顺序异常的数据行，增强排列组合尝试。
        """
        if not os.path.exists(path):
            self.logger.error(f"站点文件不存在: {path}")
            return False
        try:
            async with aiofiles.open(path, mode="r", encoding="utf-8") as f:
                content = await f.read()
            self.logger.debug(f"成功读取站点文件，大小: {len(content)}字节")
        except Exception as e:
            self.logger.error(f"读取站点文件失败: {str(e)}")
            return False
        m = re.search(r"var station_names ?= ?'(.*?)';", content)
        if not m:
            self.logger.debug("未找到var station_names模式，尝试其他模式")
            m = re.search(r"'(@[^']+)';", content)
        if not m:
            self.logger.error("未能解析到站点JS内容")
            # 输出部分内容用于调试
            self.logger.debug(f"文件前1000字符: {content[:1000]}")
            return
        data = m.group(1)
        stations_raw = [s for s in data.split('@') if s]

        result = []
        for st in stations_raw:
            parts = st.split('|')
            if len(parts) < 8:
                self.logger.warning(f"字段数异常，跳过：{st}")
                continue
            # 正确解析顺序：@id|车站名|三字码|拼音|简拼|编号|区域码|城市|...
            try:
                name = parts[1].strip()
                code = parts[2].strip()
                pinyin = parts[3].strip()
                py_short = parts[4].strip()
                num = parts[5].strip()
                city = parts[7].strip()
                # self.logger.debug(f"解析车站: {name}, {code}, {pinyin}, {py_short}, {city}")
                result.append(Station(name, code, pinyin, py_short, num, city))
            except IndexError as e:
                self.logger.warning(f"解析车站数据时出错: {st}, 错误: {e}")
                continue
        self.stations = result
        if self.stations:
            self.logger.info(f"已加载{len(self.stations)}个车站，第一个车站: {self.stations[0]}")
        else:
            self.logger.warning("未加载到任何车站数据")
        return True

    async def get_station_by_name(self, name):
        name = name.strip()
        if name.endswith("站") and len(name) > 2:
            name = name[:-1]
        for s in self.stations:
            if s.name.strip() == name:
                return s
        return None

    async def get_station_by_code(self, code):
        for s in self.stations:
            if s.code == code:
                return s
        return None

    async def search_stations(self, query, limit=10):
        query = query.strip().lower()
        results = []
        matched_ids = set()
        # 1. 精确匹配
        for s in self.stations:
            if (query == s.name.strip().lower() or
                query == s.code.lower() or
                query == s.pinyin.lower() or
                query == s.py_short.lower() or
                (s.city and query == s.city.lower())):
                results.append(s)
                matched_ids.add(id(s))
                if len(results) >= limit:
                    return StationSearchResult(results)
        # 2. 模糊匹配（含city）
        for s in self.stations:
            if id(s) in matched_ids:
                continue
            if (query in s.name.strip().lower() or
                query in s.pinyin.lower() or
                query in s.py_short.lower() or
                query in s.code.lower() or
                (s.city and query in s.city.lower())):
                results.append(s)
                if len(results) >= limit:
                    break
        return StationSearchResult(results)

    async def get_station_code(self, query: str) -> Optional[str]:
        if not query:
            return None
        q = query.strip()
        # 兼容“站”
        if q.endswith("站") and len(q) > 2:
            q = q[:-1]
        # 1. 精确匹配 name（区分大小写，通常为中文）
        for s in self.stations:
            if q == s.name:
                return s.code
        # 2. 精确匹配 code（三字码，区分大小写，通常为大写）
        for s in self.stations:
            if q == s.code:
                return s.code
        return None